package com.kf.config.shiro;
 


import com.kf.pojo.User;
import com.kf.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;


import javax.annotation.Resource;


/**
 * 电话号码领域
 *
 * @author Honey
 * @date 2022/12/17
 */
public class PhoneCodeRealm extends AuthorizingRealm {

    @Resource
     UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        PhoneCodeToken phoneToken=(PhoneCodeToken) token;
        String phone = (String) phoneToken.getPrincipal();
        User user = userService.findByPhone(phone);
        Subject subject = SecurityUtils.getSubject();
        if(user == null){
            throw new UnknownAccountException("手机号有误");
        }
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);
        return new SimpleAuthenticationInfo(user,phone,getName());
    }
 
    /**
     * 用来判断是否使用当前的 realm
     * @param var1 传入的token
     * @return true就使用，false就不使用
     */
    @Override
    public boolean supports(AuthenticationToken var1) {
        return var1 instanceof PhoneCodeToken;
    }
}